<template>
	<canvas ref="canvasRef" class="canvas"></canvas>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const canvasRef = ref(null);
let ctx;
const mouse = { x: 0, y: 0 };
const gravity = 0.03;
const friction = 0.99;
let particleArray = [];

class Particle {
	constructor(x, y, radius, color, velocity) {
		this.x = x;
		this.y = y;
		this.radius = radius;
		this.color = color;
		this.velocity = velocity;
		this.alpha = 1;
	}
	
	draw() {
		ctx.save();
		ctx.globalAlpha = this.alpha;
		ctx.beginPath();
		ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
		ctx.fillStyle = this.color;
		ctx.fill();
		ctx.closePath();
		ctx.restore();
	}
	
	update() {
		this.draw();
		this.velocity.x *= friction;
		this.velocity.y *= friction;
		this.velocity.y += gravity;
		this.x += this.velocity.x;
		this.y += this.velocity.y;
		this.alpha -= 0.003;
	}
}

function animate() {
	requestAnimationFrame(animate);
	ctx.fillStyle = `rgba(0,0,0,0.05)`;
	ctx.fillRect(0, 0, canvasRef.value.width, canvasRef.value.height);
	
	particleArray.forEach((particle, i) => {
		if (particle.alpha > 0) {
			particle.update();
		} else {
			particleArray.splice(i, 1);
		}
	});
}

onMounted(() => {
	const canvas = canvasRef.value;
	ctx = canvas.getContext('2d');
	canvas.width = window.innerWidth;
	canvas.height = window.innerHeight;
	
	mouse.x = canvas.width / 2;
	mouse.y = canvas.height / 2;
	
	window.addEventListener("resize", () => {
		canvas.width = window.innerWidth;
		canvas.height = window.innerHeight;
	});
	
	window.addEventListener('click', (event) => {
		mouse.x = event.clientX;
		mouse.y = event.clientY;
		const particleCount = 500;
		const power = 12;
		const angleIncrement = Math.PI * 2 / particleCount;
		
		for (let i = 0; i < particleCount; i++) {
			particleArray.push(
				new Particle(mouse.x, mouse.y, 2,
					`hsl(${Math.random() * 360}, 80%, 50%)`, {
						x: Math.cos(angleIncrement * i) * Math.random() * power,
						y: Math.sin(angleIncrement * i) * Math.random() * power
					}
				)
			);
		}
	});
	
	animate();
});
</script>

<style scoped>
* {
	padding: 0;
	margin: 0;
	box-sizing: border-box;
}

body {
	background: #000;
	height: 100vh;
}

canvas {
	display: flex;
}
</style>
